package com.lagou.handler;

import com.lagou.process.Processor;
import com.lagou.protocol.RpcRequest;
import com.lagou.service.holder.BaseHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof RpcRequest) {
            RpcRequest rpcRequest = (RpcRequest) msg;
            Processor processorProxy = createProcessorProxy(rpcRequest);
            String result = processorProxy.process(rpcRequest);
            ctx.writeAndFlush(result);
        }

    }

    /**
     * 创建 Processor 的动态代理，目的是为了自动处理 RpcRequest 请求
     */
    public Processor createProcessorProxy(final RpcRequest rpcRequest) {
        return (Processor) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{Processor.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String requestId = rpcRequest.getRequestId();
                String serviceName = rpcRequest.getClassName();
                String methodName = rpcRequest.getMethodName();
                Class[] parameterTypes = rpcRequest.getParameterTypes();
                Object[] parameters = rpcRequest.getParameters();

                // 从IOC容器中获取bean
                Object service = BaseHolder.getBean(serviceName);

                // 反射处理请求
                Method targetMethod = service.getClass().getMethod(methodName, parameterTypes);
                Object result = targetMethod.invoke(service, parameters);

                System.out.println("Provider已成功处理请求对象ID为[" + requestId + "]的请求。");

                return result;
            }
        });

    }

}
